<script setup>
	import { ref, nextTick, reactive, onMounted, watch } from "vue";
	import { useRouter, useRoute } from "vue-router";
	import { UploadFilled } from '@element-plus/icons-vue'
	import { fabric } from "fabric-with-erasing";
	import { frec } from '@/api/home';
	import { base64ToFile, svgToPng, clipboard } from '@/utils/index';

  const router = useRouter();
	const route = useRoute();

	// 初始化页面尺寸
	const canvasDom = ref(null);
	const uploadDOM = ref(null);
	const canvasBox = ref(null);
	const baseNum = ref(200);
	const status = ref(1);
	const formula = ref("");
	const imageUrl = ref('')
	const ocrResultType = ref(0);
	const inputTextareaBox = ref(null);

	//手写板数据
	const canvas = ref(null);
	const undoStack = ref([]); // 撤销历史记录
	const ocrResult = ref(""); // OCR 识别结果
	let fabricCanvas = null;

  // 初始化画板
	const handlePreview = (num, type = 1) => {
		if (num === 1) { rewrite(1); }
		status.value = num;
		imageUrl.value = "";
		if (num === 2) {
			nextTick(() => {
				canvasDom.value.height = canvasBox.value.offsetHeight - 2;
				canvasDom.value.width = canvasBox.value.offsetWidth - 2
				// 确保 canvas 元素已加载
				if (!fabricCanvas) {
					fabricCanvas = new fabric.Canvas("canvas");
					canvas.value = fabricCanvas;
				}
				fabricCanvas.setBackgroundColor('#ffffff', fabricCanvas.renderAll.bind(fabricCanvas))
				// 启用自由绘制模式
				fabricCanvas.isDrawingMode = true;
				fabricCanvas.freeDrawingBrush = new fabric.PencilBrush(fabricCanvas);
				//fabricCanvas.setBackgroundColor('#ffffff', fabricCanvas.renderAll.bind(canvas));
				fabricCanvas.freeDrawingBrush.width = type === 1 ? 5 : 10; // 设置画笔宽度
				fabricCanvas.freeDrawingBrush.color = type === 1 ? "black" : "#ffffff"; // 设置画笔颜色
				// 监听路径创建事件
				fabricCanvas.on("path:created", (e) => {
					undoStack.value.push({ action: "draw", object: e.path });
				});
			})
		}
	};

	// 重制手写板
	const rewrite = (type = 0) => {
    if (fabricCanvas) {
      fabricCanvas.clear();
    }
		undoStack.value = [];
		if (type === 0) {
			handlePreview(2)
		}
	};

	// 手写板擦除功能
	const deleteText = () => {
		fabricCanvas.isDrawingMode = true
		fabricCanvas.freeDrawingBrush = new fabric.EraserBrush(fabricCanvas)
		fabricCanvas.freeDrawingBrush.width = 20
		//fabricCanvas.freeDrawingBrush.inverted = true
	}

	// 提交手写板内容
	const submit = () => {
		const dataURL = fabricCanvas.toDataURL({ format: "img", quality: 1.0 });
		const file = base64ToFile(dataURL)
		uploadFile(file, 1);
	};

	// 粘贴上传图片
	const handlePaste = (event) => {
		const items = event.clipboardData.items;
		for (const item of items) {
			if (item.kind === "file") {
				const file = item.getAsFile();
				uploadFile(file, 0);
				break;
			}
		}
	};

	// 图片上传
	const uploadFile = (file, file_type = 0) => {
		let formData = new FormData();
		formData.append('img', file.raw ? file.raw : file);
		formData.append('symbol', '******');
		frec(formData).then(res => {
			if (res.code === 0) {
				let text = res['data']['results'][0]['text'];
				formula.value = text.replace(/^(\*{6})(.*?)(\*{6})$/, '$2');
				if (status.value === 2) {
					if (ocrResultType.value !== 1) {
						let w = parseInt(canvasDom.value.style.width);
						ocrResultType.value = 1;
						nextTick(() => canvasSize(w, canvasBox.value.offsetWidth))
					}
				} else {
					ocrResultType.value = 1;
					if (file_type !== 1) {
						getImgSize(URL.createObjectURL(file.raw ? file.raw : file))
					}
				}
			} else {
				let msg = res.msg ? `${res.msg}` : ''
				msg += msg === "" ? (res.code ? `code:${res.code}` : '上传失败') : "";
				ElMessage.error(msg)
			}
		}).catch(err => ElMessage.error("上传失败"))
	};

	// 调整画板大小
	const canvasSize = (oldW, newW) => {
		let objects = fabricCanvas.getObjects();
		let scaleRatio = newW / oldW;
		objects.forEach(function(object) {
			object.left = object.left * scaleRatio;
			object.top = object.top * scaleRatio;
			object.scaleX = object.scaleX * scaleRatio;
			//object.scaleY=object.scaleY* scaleRatio;
		});
		let newWidth = fabricCanvas.getWidth() * scaleRatio;
		//let newHeight = fabricCanvas.getHeight() * scaleRatio;
		fabricCanvas.setDimensions({ width: newWidth });
	}

	// 复制
	let btnLoading = reactive({ latex: false, png: false });
	const copy = async (type = 1) => {
		if (!btnLoading['latex'] && type === 1 || !btnLoading['png'] && type === 2) {
			if (type === 1) {
				btnLoading['latex'] = true;
				await clipboard(formula.value, 2);
				btnLoading['latex'] = false;
			} else {
				btnLoading['png'] = true;
				await svgToPng()
				btnLoading['png'] = false;
			}
		}
	}

	// 计算图片高度
	let img_h=null;
	const leftBoxTop = ref(null);
	const getImgSize = (url) => {
		if (status.value === 1) {
			if (ocrResultType.value === 1) {

				if(!img_h){
					nextTick(() => {
						let h0=document.getElementById('leftBox').offsetHeight;
						let h1 = leftBoxTop.value.offsetHeight;
						let h2 = uploadDOM.value.offsetHeight;
						img_h=(h0-h1-h2)*0.7;
						document.getElementById('imgBox').style=`width:100%;height:${img_h}px;overflow: hidden;margin:${(h0-h1-h2)*0.15}px auto`;
						imageUrl.value = url;
					})
				}else{
					imageUrl.value = url;
				}
			}
		}
	}

	onMounted(() => {
		if (status.value === 2) {
			canvasDom.value.height = canvasBox.value.offsetHeight - 2;
			canvasDom.value.width = canvasBox.value.offsetWidth - 2;
			baseNum.value = canvasDom.value.height;
			handlePreview(2)
		} else {
			baseNum.value = uploadDOM.value.offsetHeight - 2
		}

	});

</script>

<template>
<!--  <metainfo>-->
<!--    <template v-slot:title="{ content }">{{ content }} - Yay!</template>-->
<!--  </metainfo>-->
	<el-row class="back" :gutter="ocrResultType===1?100:0" :style="ocrResultType===1?'margin-right:0px;margin-left:0px;':''">
    <el-col id="leftBox" :sm="ocrResultType==1?10:24" :md="ocrResultType==1?12:24" :lg="ocrResultType==1?12:24" :xl="ocrResultType==1?12:24" class="flex flex-col items-center left-col" :class="ocrResultType!=1?['justify-center']:['justify-between']">
      <div class="flex flex-col items-center justify-center min-w-full" :class="ocrResultType!=1?['pb-20']:''" ref="leftBoxTop" :style="ocrResultType==1?'padding-top:10%':''">
				<h1 class="text-3xl font-bold text-[#2d54eb] mt-8">{{ $t('home.title') }}</h1>
				<p class="text-[#666666] font-semibold mt-2">{{ $t('home.subTitle') }}</p>
				<div class="text-center mt-4 w-3/4 md:w-1/2" :class="ocrResultType===1?['min-w-full']:''">
					<p class="text-[#666666]">
            {{ $t('home.description') }}
					</p>
				</div>
				<div class="flex space-x-4 mt-6">
					<button :class="['border px-4 py-2 rounded',status === 1? 'border-[#2d54eb] text-[#2d54eb]': 'border-[#858C93] text-[#858C93]']" @click="handlePreview(1)">
            {{ $t('home.uploadFile') }}
					</button>
					<button :class="['border px-4 py-2 rounded',status === 2? 'border-[#2d54eb] text-[#2d54eb]': 'border-[#858C93] text-[#858C93]']" @click="handlePreview(2)">
            {{ $t('home.handwritingPad') }}
					</button>
				</div>
			</div>
			<div v-show="status===1" class="min-w-full">
				<div id="imgBox" class="flex justify-center items-center">
					<img v-if="imageUrl" :src="imageUrl" style="display: block;height: 100%;width: auto;"  alt=""/>
				</div>
			</div>
			<div ref="uploadDOM" class="w-3/4 h-60 items-center justify-center" :class="ocrResultType===1?['min-w-full']:''" @paste="handlePaste" @dragover.prevent @drop.prevent v-if="status === 1">
				<el-upload :show-file-list="false" :on-change="uploadFile" style="height:100%;" drag ref="uploadRef" :auto-upload="false" accept=".jpg,.png">
					<el-icon class="el-icon--upload"><upload-filled /></el-icon>
					<p class="text-gray-500">{{$t('home.dragTip')}}</p>
					<p class="text-[#2d54eb] ml-2"><a href="#" class="text-[#2d54eb] underline">{{$t('home.uploadTip')}}</a></p>
				</el-upload>
			</div>
			<div v-show="status === 2" class="canvasBlock" ref="canvasBlock" style="width: 100%;">
				<div class="w-3/4 h-60 items-center justify-center" :class="ocrResultType===1?['min-w-full']:''" :style="ocrResultType!==1?'margin: 0 auto;':''">
					<div class="border border-[#627ff0] h-60 rounded-lg" ref="canvasBox" style="overflow: hidden;">
						<canvas ref="canvasDom" id="canvas" width="100%" height="100%" style="width:100%;height:100%"></canvas>
					</div>
				</div>
				<div class="flex justify-center space-x-4">
					<button @click="rewrite(0)" class="px-4 py-1 mt-2 bg-white text-blue-600 border border-blue-600 rounded-md hover:bg-blue-50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-opacity-50">
						<i class="fas fa-sync-alt"></i>{{$t('home.reset')}}
					</button>
					<!--<button @click="deleteText" class="px-4 py-2 bg-white text-red-600 border border-red-600 rounded-md hover:bg-red-50 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-opacity-50">-->
					<!--<i class="fas fa-trash-alt"></i>擦 除-->
					<!--</button>-->
					<button @click="submit(1)" class="px-4 py-1 mt-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-opacity-50">
						<i class="fas fa-check"></i>{{$t('home.submit')}}
					</button>
				</div>
			</div>
		</el-col>
		<el-col :sm="10" :md='12' id="box" v-show="ocrResultType===1" :xl="12" :lg="12" class="flex flex-col items-center justify-between" style="display: flex;">
      <h1 class="text-3xl font-bold text-[#2d54eb] mt-8" :style="ocrResultType===1?'padding-top:10%':''">{{$t('home.recognitionResult')}}</h1>
			<div class="flex-1 w-full flex flex-col justify-between">
				<div class="w-full flex justify-center items-center flex-1">
					<vue-latex :fontsize="14" id="svg" :expression="formula" display-mode />
				</div>
				<div class="w-full flex justify-center items-center flex-col">
					<div class="w-full">
						<el-button :loading="btnLoading['latex']" size="default" type="primary" plain @click="copy(1)">{{$t('home.copyLatex')}}</el-button>
						<el-button :loading="btnLoading['png']" size="default" type="primary" plain @click="copy(2)">{{$t('home.copyImage')}}</el-button>
					</div>
					<div class="w-full mt-4 relative" ref="inputTextareaBox">
						<el-input v-model="formula" :style="`height:${baseNum}px`" :rows="2" type="textarea" placeholder="" />
						<!--<div class="absolute bottom-0 left-0 top-0 right-0"></div>-->
					</div>
				</div>
			</div>
		</el-col>
	</el-row>


	<!--	<div class="mt-20 mb-10 w-full px-8">-->
	<!--		<div class="text-black">-->
	<!--			<p class="text-black">友情链接</p>-->
	<!--			<div class="flex flex-wrap space-x-4 mt-2 border-t border-b border-gray-300 py-4">-->
	<!--				<a href="#" class="text-[#999999]">PPT模板下载</a>-->
	<!--				<a href="#" class="text-[#999999]">在线题题</a>-->
	<!--				<a href="#" class="text-[#999999]">福建事业单位考试</a>-->
	<!--				<a href="#" class="text-[#999999]">散文朗诵</a>-->
	<!--				<a href="#" class="text-[#999999]">问答库</a>-->
	<!--				<a href="#" class="text-[#999999]">在线题题</a>-->
	<!--				<a href="#" class="text-[#999999]">在线教育平台</a>-->
	<!--				<a href="#" class="text-[#999999]">成人教育</a>-->
	<!--				<a href="#" class="text-[#999999]">清华大学总裁班</a>-->
	<!--				<a href="#" class="text-[#999999]">司法考试</a>-->
	<!--				<a href="#" class="text-[#999999]">人民大学在职研究生</a>-->
	<!--			</div>-->
	<!--		</div>-->
	<!--	</div>-->
	<!-- <div class="floating-menu">
		<div class="bottom-4 right-4 flex flex-col items-center">
			<div class="w-16 h-16 bg-gray-200 flex items-center justify-center">
				<i class="fas fa-qrcode text-2xl text-gray-500"></i>
			</div>
			<p class="text-gray-500 mt-2">公众号</p>
		</div>
		<div class="bottom-4 right-4 flex flex-col items-center">
			<button class="border border-gray-500 text-gray-500 px-4 py-2 rounded mt-4">
				顶部
			</button>
		</div>
	</div> -->
</template>

<style scoped lang="scss">
	.back {
		width: 100%;
		background-image: url("@/assets/img/back.png");
		background-repeat: no-repeat;
		/*设置背景不重复*/
		background-attachment: fixed;
		/*背景图片不会随着页面的滚动而滚动。*/
		background-size: 100%;
		background-color: rgba(255, 255, 255, 0.8);
		/* 设置透明度 */
	}

	.floating-menu {
		position: fixed;
		right: 20px;
		top: 90%;
		transform: translateY(-50%);
		z-index: 1000;
	}

	::v-deep(.el-upload) {
		height: 100%;

		.el-upload-dragger {
			height: 100%;
		}
	}

	::v-deep(.el-textarea__inner) {
		min-height: 100% !important;
		resize: none;
	}

	::v-deep(.left-col) {
		display: flex;
	}
</style>
